import React, { useState, useEffect } from 'react';
import { verifierApi } from '../../services/apiService';

const VerifierPage = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [successMessage, setSuccessMessage] = useState(null);
  const [activeTab, setActiveTab] = useState('age-proof');
  const [proofRequests, setProofRequests] = useState([]);
  const [verificationResults, setVerificationResults] = useState([]);
  const [presentation, setPresentation] = useState('');
  const [selectedRequest, setSelectedRequest] = useState('');
  
  // 年龄证明请求状态
  const [ageProofData, setAgeProofData] = useState({
    minAge: 18,
    allowedIssuer: ''
  });
  
  // 学位证明请求状态
  const [degreeProofData, setDegreeProofData] = useState({
    degreeType: '',
    major: '',
    allowedIssuer: ''
  });
  
  // MTP证明请求状态
  const [mtpProofData, setMtpProofData] = useState({
    credentialType: '',
    schemaUrl: '',
    allowedIssuer: ''
  });
  
  // 验证模式
  const [verifyMode, setVerifyMode] = useState('presentation'); // 'presentation', 'batch', 'credential'
  
  // 批量验证状态
  const [batchPresentations, setBatchPresentations] = useState('');
  
  // 单凭证验证状态
  const [singleCredential, setSingleCredential] = useState('');
  
  // 加载证明请求历史
  useEffect(() => {
    // 注意：实际实现中，应该从后端API获取历史记录
    // 此处简化为本地状态管理
  }, []);
  
  // 创建年龄证明请求
  const createAgeProofRequest = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const response = await verifierApi.createAgeProofRequest(ageProofData);
      if (response.success) {
        setProofRequests([...proofRequests, {
          id: response.requestId,
          type: '年龄证明',
          details: `最小年龄: ${ageProofData.minAge}岁`,
          created: new Date().toISOString(),
          proofRequest: response.proofRequest
        }]);
        alert(`证明请求已创建，请求ID: ${response.requestId}`);
        setError(null);
        setSuccessMessage('年龄证明请求创建成功');
      }
    } catch (err) {
      setError('创建年龄证明请求失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };
  
  // 创建学位证明请求
  const createDegreeProofRequest = async (e) => {
    e.preventDefault();
    if (!degreeProofData.degreeType) {
      setError('学位类型为必填项');
      return;
    }
    
    setLoading(true);
    try {
      const response = await verifierApi.createDegreeProofRequest(degreeProofData);
      if (response.success) {
        setProofRequests([...proofRequests, {
          id: response.requestId,
          type: '学位证明',
          details: `学位: ${degreeProofData.degreeType}${degreeProofData.major ? `, 专业: ${degreeProofData.major}` : ''}`,
          created: new Date().toISOString(),
          proofRequest: response.proofRequest
        }]);
        alert(`证明请求已创建，请求ID: ${response.requestId}`);
        setError(null);
        setSuccessMessage('学位证明请求创建成功');
      }
    } catch (err) {
      setError('创建学位证明请求失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };
  
  // 创建MTP证明请求
  const createMTPProofRequest = async (e) => {
    e.preventDefault();
    if (!mtpProofData.credentialType || !mtpProofData.schemaUrl) {
      setError('凭证类型和Schema URL为必填项');
      return;
    }
    
    setLoading(true);
    try {
      const response = await verifierApi.createMTPProofRequest(mtpProofData);
      if (response.success) {
        setProofRequests([...proofRequests, {
          id: response.requestId,
          type: 'MTP证明',
          details: `类型: ${mtpProofData.credentialType}`,
          created: new Date().toISOString(),
          proofRequest: response.proofRequest
        }]);
        alert(`证明请求已创建，请求ID: ${response.requestId}`);
        setError(null);
        setSuccessMessage('MTP证明请求创建成功');
      }
    } catch (err) {
      setError('创建MTP证明请求失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };
  
  // 验证可验证演示(VP)
  const verifyPresentation = async (e) => {
    e.preventDefault();
    if (!presentation) {
      setError('可验证演示(VP)是必填项');
      return;
    }
    
    console.log("开始验证演示...");
    setLoading(true);
    try {
      let parsedPresentation;
      try {
        parsedPresentation = JSON.parse(presentation);
        console.log("JSON解析成功:", parsedPresentation);
      } catch (parseError) {
        console.error("JSON解析错误:", parseError);
        setError('无效的JSON格式: ' + parseError.message);
        setLoading(false);
        return;
      }
      
      console.log("调用API验证演示, requestId:", selectedRequest || "无");
      
      try {
        const response = await verifierApi.verifyPresentation(
          parsedPresentation, 
          selectedRequest || undefined
        );
        
        console.log("API响应:", response);
        
        if (response && response.success) {
          console.log("验证成功, 结果:", response.verificationResult);
          
          // 获取验证的状态和详细信息
          const isValid = response.verificationResult.success || response.verificationResult.valid;
          const checksDetails = response.verificationResult.checks || {};
          const errorMessages = response.verificationResult.errors || [];
          
          // 构建详细的结果消息
          let resultMessage = isValid ? '验证成功' : '验证失败';
          
          if (!isValid && errorMessages.length > 0) {
            resultMessage += ': ' + errorMessages.join('; ');
          }
          
          // 构建检查详情
          const checksInfo = Object.entries(checksDetails)
            .map(([key, value]) => `${key}: ${value ? '✓' : '✗'}`)
            .join(', ');
          
          setVerificationResults([
            {
              id: response.verificationId,
              timestamp: new Date().toISOString(),
              result: resultMessage,
              details: response.verificationResult,
              checksInfo,
              holder: response.verificationResult.holder
            },
            ...verificationResults
          ]);
          
          setPresentation('');
          setSelectedRequest('');
          setError(null);
          setSuccessMessage(`验证完成: ${resultMessage}`);
        } else {
          console.error("API响应缺少success属性或为false:", response);
          setError(response && response.error ? response.error : '验证失败，服务器响应格式错误');
        }
      } catch (apiError) {
        console.error("API调用失败:", apiError);
        setError('API调用失败: ' + (apiError.message || '未知错误'));
      }
    } catch (err) {
      console.error("验证过程中发生错误:", err);
      setError('验证演示失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
      console.log("验证过程结束");
    }
  };
  
  // 批量验证可验证演示(VPs)
  const verifyBatchPresentations = async (e) => {
    e.preventDefault();
    if (!batchPresentations) {
      setError('批量可验证演示数据是必填项');
      return;
    }
    
    console.log("开始批量验证...");
    setLoading(true);
    try {
      let parsedData;
      try {
        parsedData = JSON.parse(batchPresentations);
        console.log("批量数据JSON解析成功:", parsedData);
        
        // 确保是数组格式
        if (!Array.isArray(parsedData)) {
          // 尝试转换为数组格式
          if (typeof parsedData === 'object') {
            parsedData = [{ presentation: parsedData }];
            console.log("转换单个对象为数组:", parsedData);
          } else {
            throw new Error('数据必须是数组或单个VP对象');
          }
        } else {
          // 确保每个元素都有presentation字段
          parsedData = parsedData.map(item => {
            if (item.presentation) return item;
            return { presentation: item }; // 假设直接是VP对象
          });
          console.log("处理后的数据结构:", parsedData);
        }
      } catch (parseError) {
        console.error("批量JSON解析错误:", parseError);
        setError('无效的JSON格式: ' + parseError.message);
        setLoading(false);
        return;
      }
      
      console.log("调用批量验证API...");
      const response = await verifierApi.verifyBatchPresentations(parsedData);
      console.log("批量API响应:", response);
      
      if (response && response.success) {
        console.log("批量验证成功, 结果:", response.batchResult);
        // 添加批量验证结果
        setVerificationResults([
          {
            id: response.verificationId,
            timestamp: new Date().toISOString(),
            result: `批量验证: ${response.batchResult.validCount}/${response.batchResult.count} 有效`,
            details: response.batchResult,
            holder: '多个'
          },
          ...verificationResults
        ]);
        
        // 添加每个单独的验证结果
        const individualResults = response.batchResult.results.map(result => ({
          id: result.id,
          timestamp: new Date().toISOString(),
          result: result.valid ? '验证成功' : '验证失败',
          details: result,
          holder: result.holder || 'N/A'
        }));
        
        setVerificationResults([
          ...individualResults,
          ...verificationResults
        ]);
        
        setBatchPresentations('');
        setError(null);
        setSuccessMessage(`批量验证完成: ${response.batchResult.validCount}/${response.batchResult.count} 有效`);
      } else {
        console.error("批量API响应缺少success属性或为false:", response);
        setError(response && response.error ? response.error : '批量验证失败，服务器响应格式错误');
      }
    } catch (err) {
      console.error("批量验证过程中发生错误:", err);
      setError('批量验证失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
      console.log("批量验证过程结束");
    }
  };
  
  // 验证单个可验证凭证(VC)
  const verifyCredential = async (e) => {
    e.preventDefault();
    if (!singleCredential) {
      setError('可验证凭证(VC)是必填项');
      return;
    }
    
    console.log("开始验证单个凭证...");
    setLoading(true);
    try {
      let parsedCredential;
      try {
        parsedCredential = JSON.parse(singleCredential);
        console.log("凭证JSON解析成功:", parsedCredential);
      } catch (parseError) {
        console.error("凭证JSON解析错误:", parseError);
        setError('无效的JSON格式: ' + parseError.message);
        setLoading(false);
        return;
      }
      
      console.log("调用凭证验证API...");
      const response = await verifierApi.verifyCredential(parsedCredential);
      console.log("凭证验证API响应:", response);
      
      if (response && response.success) {
        console.log("凭证验证成功, 结果:", response.verificationResult);
        setVerificationResults([
          {
            id: response.verificationId,
            timestamp: new Date().toISOString(),
            result: response.verificationResult.valid ? '验证成功' : '验证失败',
            details: response.verificationResult,
            holder: '直接凭证验证'
          },
          ...verificationResults
        ]);
        
        setSingleCredential('');
        setError(null);
        setSuccessMessage('凭证验证完成，结果: ' + (response.verificationResult.valid ? '验证成功' : '验证失败'));
      } else {
        console.error("凭证验证API响应缺少success属性或为false:", response);
        setError(response && response.error ? response.error : '凭证验证失败，服务器响应格式错误');
      }
    } catch (err) {
      console.error("凭证验证过程中发生错误:", err);
      setError('验证凭证失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
      console.log("凭证验证过程结束");
    }
  };

  const [activeVerificationResult, setActiveVerificationResult] = useState(null);

  // 错误和成功消息的处理函数
  const clearMessages = () => {
    setError(null);
    setSuccessMessage(null);
  };

  return (
    <div className="container py-4">
      {/* 错误提示 */}
      {error && (
        <div className="alert alert-danger mb-4" role="alert">
          <i className="bi bi-exclamation-triangle-fill me-2"></i> {error}
          <button type="button" className="btn-close float-end" onClick={() => setError(null)}></button>
        </div>
      )}
      
      {/* 成功提示 */}
      {successMessage && (
        <div className="alert alert-success mb-4" role="alert">
          <i className="bi bi-check-circle-fill me-2"></i> {successMessage}
          <button type="button" className="btn-close float-end" onClick={() => setSuccessMessage(null)}></button>
        </div>
      )}
      
      {/* 标签栏 */}
      <ul className="nav nav-tabs mb-4">
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'age-proof' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('age-proof');
              clearMessages();
            }}>
            年龄证明
          </button>
        </li>
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'degree-proof' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('degree-proof');
              clearMessages();
            }}>
            学位证明
          </button>
        </li>
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'mtp-proof' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('mtp-proof');
              clearMessages();
            }}>
            MTP证明
          </button>
        </li>
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'verify' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('verify');
              clearMessages();
            }}>
            验证凭证
          </button>
        </li>
        <li className="nav-item">
          <button 
            className={`nav-link ${activeTab === 'history' ? 'active' : ''}`}
            onClick={() => {
              setActiveTab('history');
              clearMessages();
            }}>
            验证历史
          </button>
        </li>
      </ul>
      
      {/* 年龄证明请求 */}
      {activeTab === 'age-proof' && (
        <div className="card">
          <div className="card-body">
            <h3 className="card-title mb-3">创建年龄证明请求</h3>
            <p className="text-muted mb-4">
              创建一个要求证明持有者年龄大于等于指定值的请求
            </p>
            
            <form onSubmit={createAgeProofRequest}>
              <div className="mb-3">
                <label className="form-label">最小年龄</label>
                <input 
                  type="number"
                  className="form-control"
                  value={ageProofData.minAge}
                  onChange={(e) => setAgeProofData({
                    ...ageProofData, 
                    minAge: e.target.value
                  })}
                  min="1"
                  required
                />
              </div>
              <div className="mb-3">
                <label className="form-label">允许的发行方DID (可选)</label>
                <input 
                  type="text"
                  className="form-control"
                  value={ageProofData.allowedIssuer}
                  onChange={(e) => setAgeProofData({
                    ...ageProofData, 
                    allowedIssuer: e.target.value
                  })}
                  placeholder="例如: did:polygonid:polygon:amoy:2qEf..."
                />
                <div className="form-text">
                  限定哪些发行方的凭证可以用于证明。留空表示接受任何发行方。
                </div>
              </div>
              <button 
                type="submit" 
                className="btn btn-primary"
                disabled={loading}>
                {loading ? '处理中...' : '创建证明请求'}
              </button>
            </form>
          </div>
        </div>
      )}
      
      {/* 学位证明请求 */}
      {activeTab === 'degree-proof' && (
        <div className="card">
          <div className="card-body">
            <h3 className="card-title mb-3">创建学位证明请求</h3>
            <p className="text-muted mb-4">
              创建一个要求证明持有者拥有指定学位类型的请求
            </p>
            
            <form onSubmit={createDegreeProofRequest}>
              <div className="mb-3">
                <label className="form-label">学位类型</label>
                <select 
                  className="form-select"
                  value={degreeProofData.degreeType}
                  onChange={(e) => setDegreeProofData({
                    ...degreeProofData, 
                    degreeType: e.target.value
                  })}
                  required>
                  <option value="">选择学位类型</option>
                  <option value="Bachelor">学士</option>
                  <option value="Master">硕士</option>
                  <option value="PhD">博士</option>
                  <option value="Associate">专科</option>
                </select>
              </div>
              <div className="mb-3">
                <label className="form-label">专业 (可选)</label>
                <input 
                  type="text"
                  className="form-control"
                  value={degreeProofData.major}
                  onChange={(e) => setDegreeProofData({
                    ...degreeProofData, 
                    major: e.target.value
                  })}
                  placeholder="例如: 计算机科学"
                />
              </div>
              <div className="mb-3">
                <label className="form-label">允许的发行方DID (可选)</label>
                <input 
                  type="text"
                  className="form-control"
                  value={degreeProofData.allowedIssuer}
                  onChange={(e) => setDegreeProofData({
                    ...degreeProofData, 
                    allowedIssuer: e.target.value
                  })}
                  placeholder="例如: did:polygonid:polygon:amoy:2qEf..."
                />
              </div>
              <button 
                type="submit" 
                className="btn btn-primary"
                disabled={loading}>
                {loading ? '处理中...' : '创建证明请求'}
              </button>
            </form>
          </div>
        </div>
      )}
      
      {/* MTP证明请求 */}
      {activeTab === 'mtp-proof' && (
        <div className="card">
          <div className="card-body">
            <h3 className="card-title mb-3">创建MTP证明请求</h3>
            <p className="text-muted mb-4">
              创建一个要求证明持有者拥有指定类型凭证且状态有效的请求
            </p>
            
            <form onSubmit={createMTPProofRequest}>
              <div className="mb-3">
                <label className="form-label">凭证类型</label>
                <input 
                  type="text"
                  className="form-control"
                  value={mtpProofData.credentialType}
                  onChange={(e) => setMtpProofData({
                    ...mtpProofData, 
                    credentialType: e.target.value
                  })}
                  placeholder="例如: AcademicDegree"
                  required
                />
              </div>
              <div className="mb-3">
                <label className="form-label">Schema URL</label>
                <input 
                  type="text"
                  className="form-control"
                  value={mtpProofData.schemaUrl}
                  onChange={(e) => setMtpProofData({
                    ...mtpProofData, 
                    schemaUrl: e.target.value
                  })}
                  placeholder="例如: https://eduverse.example.com/schemas/academic-degree.jsonld"
                  required
                />
              </div>
              <div className="mb-3">
                <label className="form-label">允许的发行方DID (可选)</label>
                <input 
                  type="text"
                  className="form-control"
                  value={mtpProofData.allowedIssuer}
                  onChange={(e) => setMtpProofData({
                    ...mtpProofData, 
                    allowedIssuer: e.target.value
                  })}
                  placeholder="例如: did:polygonid:polygon:amoy:2qEf..."
                />
              </div>
              <button 
                type="submit" 
                className="btn btn-primary"
                disabled={loading}>
                {loading ? '处理中...' : '创建证明请求'}
              </button>
            </form>
          </div>
        </div>
      )}
      
      {/* 验证凭证 */}
      {activeTab === 'verify' && (
        <div className="card">
          <div className="card-body">
            <h3 className="card-title mb-3">验证凭证</h3>
            <p className="text-muted mb-4">
              验证持有者提供的凭证数据是否有效
            </p>
            
            {/* 验证模式选择 */}
            <ul className="nav nav-pills mb-4">
              <li className="nav-item">
                <button 
                  className={`nav-link ${verifyMode === 'presentation' ? 'active' : ''}`}
                  onClick={() => {
                    setVerifyMode('presentation');
                    clearMessages();
                  }}>
                  验证单个演示(VP)
                </button>
              </li>
              <li className="nav-item">
                <button 
                  className={`nav-link ${verifyMode === 'batch' ? 'active' : ''}`}
                  onClick={() => {
                    setVerifyMode('batch');
                    clearMessages();
                  }}>
                  批量验证
                </button>
              </li>
              <li className="nav-item">
                <button 
                  className={`nav-link ${verifyMode === 'credential' ? 'active' : ''}`}
                  onClick={() => {
                    setVerifyMode('credential');
                    clearMessages();
                  }}>
                  直接验证凭证(VC)
                </button>
              </li>
            </ul>
            
            {/* 单个VP验证表单 */}
            {verifyMode === 'presentation' && (
              <form onSubmit={verifyPresentation}>
                <div className="mb-3">
                  <label className="form-label">请求ID (可选)</label>
                  <select 
                    className="form-select"
                    value={selectedRequest}
                    onChange={(e) => setSelectedRequest(e.target.value)}>
                    <option value="">选择请求ID</option>
                    {proofRequests.map(req => (
                      <option key={req.id} value={req.id}>
                        {req.id} - {req.type} ({new Date(req.created).toLocaleString()})
                      </option>
                    ))}
                  </select>
                  <div className="form-text">
                    如果VP是针对特定请求生成的，选择对应的请求ID以验证挑战。
                  </div>
                </div>
                <div className="mb-3">
                  <label className="form-label">可验证演示 (VP) JSON</label>
                  <textarea 
                    className="form-control"
                    rows="10"
                    value={presentation}
                    onChange={(e) => setPresentation(e.target.value)}
                    placeholder="粘贴VP JSON数据"
                    required
                  />
                  <button 
                    type="button" 
                    className="btn btn-sm btn-outline-secondary mt-2"
                    onClick={() => {
                      setPresentation(JSON.stringify({
                        "@context": ["https://www.w3.org/ns/credentials/v2"],
                        "id": "test-vp-" + Date.now(),
                        "type": ["VerifiablePresentation"],
                        "holder": "did:example:holder",
                        "verifiableCredential": [{
                          "@context": ["https://www.w3.org/ns/credentials/v2"],
                          "id": "test-vc-" + Date.now(),
                          "type": ["VerifiableCredential"],
                          "issuer": "did:example:issuer",
                          "credentialSubject": {
                            "id": "did:example:subject",
                            "name": "测试凭证"
                          }
                        }]
                      }, null, 2));
                    }}>
                    填充测试数据
                  </button>
                </div>
                <button 
                  type="submit" 
                  className="btn btn-primary"
                  disabled={loading}>
                  {loading ? '处理中...' : '验证演示'}
                </button>
              </form>
            )}
            
            {/* 批量验证表单 */}
            {verifyMode === 'batch' && (
              <form onSubmit={verifyBatchPresentations}>
                <div className="mb-3">
                  <label className="form-label">批量可验证演示数据</label>
                  <div className="form-text mb-2">
                    可以是VP对象数组，或包含presentation字段的对象数组。每个对象可以包含requestId字段指定对应的请求ID。
                  </div>
                  <textarea 
                    className="form-control"
                    rows="12"
                    value={batchPresentations}
                    onChange={(e) => setBatchPresentations(e.target.value)}
                    placeholder="粘贴批量VP数据，格式如: [{ presentation: {...}, requestId: '...' }, ...]"
                    required
                  />
                  <button 
                    type="button" 
                    className="btn btn-sm btn-outline-secondary mt-2"
                    onClick={() => {
                      const now = Date.now();
                      setBatchPresentations(JSON.stringify([
                        {
                          presentation: {
                            "@context": ["https://www.w3.org/ns/credentials/v2"],
                            "id": "test-vp-1-" + now,
                            "type": ["VerifiablePresentation"],
                            "holder": "did:example:holder1",
                            "verifiableCredential": [{
                              "@context": ["https://www.w3.org/ns/credentials/v2"],
                              "id": "test-vc-1-" + now,
                              "type": ["VerifiableCredential"],
                              "issuer": "did:example:issuer",
                              "credentialSubject": {
                                "id": "did:example:subject1",
                                "name": "测试凭证1"
                              }
                            }]
                          }
                        },
                        {
                          presentation: {
                            "@context": ["https://www.w3.org/ns/credentials/v2"],
                            "id": "test-vp-2-" + now,
                            "type": ["VerifiablePresentation"],
                            "holder": "did:example:holder2",
                            "verifiableCredential": [{
                              "@context": ["https://www.w3.org/ns/credentials/v2"],
                              "id": "test-vc-2-" + now,
                              "type": ["VerifiableCredential"],
                              "issuer": "did:example:issuer",
                              "credentialSubject": {
                                "id": "did:example:subject2",
                                "name": "测试凭证2"
                              }
                            }]
                          }
                        }
                      ], null, 2));
                    }}>
                    填充测试数据
                  </button>
                </div>
                <button 
                  type="submit" 
                  className="btn btn-primary"
                  disabled={loading}>
                  {loading ? '处理中...' : '批量验证'}
                </button>
              </form>
            )}
            
            {/* 直接验证凭证表单 */}
            {verifyMode === 'credential' && (
              <form onSubmit={verifyCredential}>
                <div className="mb-3">
                  <label className="form-label">可验证凭证 (VC) JSON</label>
                  <div className="form-text mb-2">
                    直接验证单个凭证，不需要VP包装。系统将检查签名、撤销状态和过期时间。
                  </div>
                  <textarea 
                    className="form-control"
                    rows="10"
                    value={singleCredential}
                    onChange={(e) => setSingleCredential(e.target.value)}
                    placeholder="粘贴VC JSON数据"
                    required
                  />
                  <button 
                    type="button" 
                    className="btn btn-sm btn-outline-secondary mt-2"
                    onClick={() => {
                      setSingleCredential(JSON.stringify({
                        "@context": ["https://www.w3.org/ns/credentials/v2"],
                        "id": "test-vc-" + Date.now(),
                        "type": ["VerifiableCredential"],
                        "issuer": "did:example:issuer",
                        "issuanceDate": new Date().toISOString(),
                        "credentialSubject": {
                          "id": "did:example:subject",
                          "name": "测试凭证",
                          "degree": "Bachelor",
                          "major": "Computer Science"
                        }
                      }, null, 2));
                    }}>
                    填充测试数据
                  </button>
                </div>
                <button 
                  type="submit" 
                  className="btn btn-primary"
                  disabled={loading}>
                  {loading ? '处理中...' : '验证凭证'}
                </button>
              </form>
            )}
          </div>
        </div>
      )}
      
      {/* 验证历史 */}
      {activeTab === 'history' && (
        <div className="card">
          <div className="card-body">
            <h3 className="card-title mb-3">验证历史</h3>
            {verificationResults.length === 0 ? (
              <p className="text-muted">暂无验证记录</p>
            ) : (
              <div className="table-responsive">
                <table className="table table-hover">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>时间</th>
                      <th>持有者</th>
                      <th>结果</th>
                      <th>详情</th>
                    </tr>
                  </thead>
                  <tbody>
                    {verificationResults.map(result => (
                      <tr key={result.id}>
                        <td><small>{result.id}</small></td>
                        <td>{new Date(result.timestamp).toLocaleString()}</td>
                        <td><small>{result.holder || 'N/A'}</small></td>
                        <td>
                          {result.result === '验证成功' ? 
                            <span className="badge bg-success">验证成功</span> :
                            <span className="badge bg-danger">验证失败</span>
                          }
                        </td>
                        <td>
                          <button 
                            className="btn btn-sm btn-outline-info"
                            onClick={() => setActiveVerificationResult(result)}>
                            查看详情
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
            
            <div className="mt-4">
              <h5>证明请求列表</h5>
              {proofRequests.length === 0 ? (
                <p className="text-muted">暂无证明请求记录</p>
              ) : (
                <div className="table-responsive">
                  <table className="table table-hover">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>类型</th>
                        <th>日期</th>
                        <th>详情</th>
                        <th>操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      {proofRequests.map(request => (
                        <tr key={request.id}>
                          <td><small>{request.id}</small></td>
                          <td>{request.type}</td>
                          <td>{new Date(request.created).toLocaleString()}</td>
                          <td>{request.details}</td>
                          <td>
                            <button 
                              className="btn btn-sm btn-outline-info"
                              onClick={() => {
                                setSelectedRequest(request.id);
                                setActiveTab('verify');
                              }}>
                              使用此请求验证
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
      
      {/* 验证结果详情模态框 */}
      {activeVerificationResult && (
        <div className="modal fade show" style={{ display: 'block' }} tabIndex="-1">
          <div className="modal-dialog modal-lg modal-dialog-scrollable">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">验证结果详情</h5>
                <button type="button" className="btn-close" onClick={() => setActiveVerificationResult(null)}></button>
              </div>
              <div className="modal-body">
                <div className="card mb-3">
                  <div className="card-header">
                    <h6 className="mb-0">基本信息</h6>
                  </div>
                  <div className="card-body">
                    <p><strong>ID:</strong> {activeVerificationResult.id}</p>
                    <p><strong>验证时间:</strong> {new Date(activeVerificationResult.timestamp).toLocaleString()}</p>
                    <p><strong>持有者DID:</strong> {activeVerificationResult.holder || 'N/A'}</p>
                    <p>
                      <strong>整体结果:</strong> 
                      {activeVerificationResult.result === '验证成功' ? 
                        <span className="badge bg-success ms-2">验证成功</span> :
                        <span className="badge bg-danger ms-2">验证失败</span>
                      }
                    </p>
                    
                    {activeVerificationResult.checksInfo && (
                      <p>
                        <strong>检查项详情:</strong> 
                        <code className="ms-2">{activeVerificationResult.checksInfo}</code>
                      </p>
                    )}
                  </div>
                </div>

                {activeVerificationResult.details && (
                  <>
                    {/* 验证检查项 */}
                    <div className="card mb-3">
                      <div className="card-header">
                        <h6 className="mb-0">验证检查项</h6>
                      </div>
                      <div className="card-body">
                        <table className="table table-bordered">
                          <tbody>
                            {activeVerificationResult.details.checks && Object.entries(activeVerificationResult.details.checks).map(([key, value]) => (
                              <tr key={key}>
                                <td>{key}</td>
                                <td>
                                  {value ? 
                                    <span className="badge bg-success">通过</span> :
                                    <span className="badge bg-danger">失败</span>
                                  }
                                </td>
                              </tr>
                            ))}
                            
                            {!activeVerificationResult.details.checks && (
                              <>
                                <tr>
                                  <td>VP签名验证</td>
                                  <td>
                                    {activeVerificationResult.details.vpSignatureValid === null ? 
                                      <span className="badge bg-secondary">不适用</span> :
                                      activeVerificationResult.details.vpSignatureValid ? 
                                        <span className="badge bg-success">通过</span> :
                                        <span className="badge bg-danger">失败</span>
                                    }
                                  </td>
                                </tr>
                                <tr>
                                  <td>零知识证明验证</td>
                                  <td>
                                    {activeVerificationResult.details.zkpValid === null ? 
                                      <span className="badge bg-secondary">不适用</span> :
                                      activeVerificationResult.details.zkpValid ? 
                                        <span className="badge bg-success">通过</span> :
                                        <span className="badge bg-danger">失败</span>
                                    }
                                  </td>
                                </tr>
                                <tr>
                                  <td>凭证签名验证</td>
                                  <td>
                                    {activeVerificationResult.details.vcSignatureValid === null ? 
                                      <span className="badge bg-secondary">不适用</span> :
                                      activeVerificationResult.details.vcSignatureValid ? 
                                        <span className="badge bg-success">通过</span> :
                                        <span className="badge bg-danger">失败</span>
                                    }
                                  </td>
                                </tr>
                              </>
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                    
                    {/* 错误信息展示 */}
                    {activeVerificationResult.details.errors && activeVerificationResult.details.errors.length > 0 && (
                      <div className="card mb-3">
                        <div className="card-header bg-danger text-white">
                          <h6 className="mb-0">验证错误</h6>
                        </div>
                        <div className="card-body">
                          <ul className="list-group">
                            {activeVerificationResult.details.errors.map((error, idx) => (
                              <li key={idx} className="list-group-item text-danger">{error}</li>
                            ))}
                          </ul>
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" onClick={() => setActiveVerificationResult(null)}>关闭</button>
              </div>
            </div>
          </div>
        </div>
      )}
      
      {activeVerificationResult && <div className="modal-backdrop fade show"></div>}
    </div>
  );
};

export default VerifierPage; 